<?php

namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\LevelService;
use xy_jx\Utils\Excel;

class LevelLogic extends BackendLogic
{


    public function __construct()
    {
        $this->service = Container::get(LevelService::class);
    }

    public function getList(): array
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['name']) && $param['name']) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = $this->service->getListPage($where, ['*'], ['id' => 'desc'], [], request()->get('limit', 10));
        return message($list);
    }

    /**
     * 获取职级列表
     * @return array
     * @since 2020/11/20
     */
    public function getLevelList()
    {
        $list = $this->service->getLevelList();
        return message($list);
    }

    public function edit(): array
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['name'])) throw new ApiException('请输入职位名称');
        if (empty($data['sort'])) throw new ApiException('请输入排序');
        $save['name'] = trim($data['name']);
        $save['sort'] = $data['sort'];
        $save['status'] = $data['status'] ?? 1;
        unset($data['id']);
        if ($id == 0) {
            $this->service->add($save);
        } else {
            $this->service->save($save, $id);
        }
        return message();

    }


    public function exportExcel()
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['name']) && $param['name']) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = $this->service->getList($where);
        Excel::header('职级管理', ['id' => '职级ID', 'name' => '职级名称', 'status' => '职级状态', 'sort' => '职级排序'])
            ->content($list)->save('Xlsx', false, '职级管理.xlsx');
    }

}
